"""
日志窗口
"""
from PyQt6.QtWidgets import (QDialog, QVBoxLayout, QTextEdit, 
                           QPushButton, QHBoxLayout)
from PyQt6.QtCore import Qt, QTimer
import os
import time

class LogDialog(QDialog):
    """日志窗口"""
    
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowTitle("扫货日志")
        self.resize(800, 600)
        self.setup_ui()
        
        # 定时器，用于定期刷新日志
        self.timer = QTimer()
        self.timer.timeout.connect(self.update_log)
        self.timer.start(1000)  # 每秒更新一次
        
        # 记录上次读取的位置
        self.last_position = 0
        
    def setup_ui(self):
        """初始化UI"""
        layout = QVBoxLayout(self)
        layout.setContentsMargins(20, 20, 20, 20)
        layout.setSpacing(20)
        
        # 日志文本框
        self.log_text = QTextEdit()
        self.log_text.setReadOnly(True)
        self.log_text.setStyleSheet("""
            QTextEdit {
                border: 1px solid #d9d9d9;
                border-radius: 4px;
                padding: 10px;
                font-family: Consolas, Monaco, monospace;
                font-size: 12px;
                line-height: 1.5;
                background-color: #f5f5f5;
            }
        """)
        
        # 按钮区域
        button_layout = QHBoxLayout()
        
        # 清空按钮
        self.clear_btn = QPushButton("清空")
        self.clear_btn.clicked.connect(self.clear_log)
        self.clear_btn.setStyleSheet("""
            QPushButton {
                background-color: white;
                border: 1px solid #d9d9d9;
                border-radius: 4px;
                color: rgba(0, 0, 0, 0.85);
                padding: 5px 15px;
                font-size: 14px;
            }
            QPushButton:hover {
                border-color: #40a9ff;
                color: #40a9ff;
            }
        """)
        
        # 关闭按钮
        self.close_btn = QPushButton("关闭")
        self.close_btn.clicked.connect(self.close)
        self.close_btn.setStyleSheet("""
            QPushButton {
                background-color: #1890ff;
                border: none;
                border-radius: 4px;
                color: white;
                padding: 5px 15px;
                font-size: 14px;
            }
            QPushButton:hover {
                background-color: #40a9ff;
            }
            QPushButton:pressed {
                background-color: #096dd9;
            }
        """)
        
        button_layout.addWidget(self.clear_btn)
        button_layout.addStretch()
        button_layout.addWidget(self.close_btn)
        
        layout.addWidget(self.log_text)
        layout.addLayout(button_layout)
        
    def update_log(self):
        """更新日志内容"""
        try:
            # 获取日志文件路径
            log_file = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), 
                                  "logs", "scan.log")
            
            if not os.path.exists(log_file):
                return
                
            # 读取新的日志内容
            with open(log_file, "r", encoding="utf-8") as f:
                # 如果文件大小变小了，说明文件被重新创建
                current_size = os.path.getsize(log_file)
                if current_size < self.last_position:
                    self.last_position = 0
                    
                f.seek(self.last_position)
                new_content = f.read()
                
                if new_content:
                    # 添加新内容到文本框
                    self.log_text.append(new_content)
                    # 滚动到底部
                    self.log_text.verticalScrollBar().setValue(
                        self.log_text.verticalScrollBar().maximum()
                    )
                    # 更新位置
                    self.last_position = f.tell()
                    
        except Exception as e:
            print(f"更新日志出错: {e}")
            
    def clear_log(self):
        """清空日志"""
        self.log_text.clear()
        
    def closeEvent(self, event):
        """关闭窗口时停止定时器"""
        self.timer.stop()
        super().closeEvent(event)
